import { memo, useCallback, useEffect, useRef, useState } from 'react';
import type { ReactNode, FC } from 'react';
import { Descriptions, Slider, message } from 'antd';

import {
  CtrlWrapper,
  OperWrapper,
  PlayerBarContentWrapper,
  PlayerBarWrapper,
  PlayerWrapper,
  PlayerBarAWrapper,
} from './style';
import { shallowEqualApp, useAppDispatch, useAppSelector } from '@/store/hooks';
import { getPlayUrl, formatTime } from '@/utils/format';
import { changeCurrentSong, setLyricIndex, setPlayMode } from '../store/player';
import PlayerbarList from './c-cps/playerbarList';
import VoiceRange from './c-cps/voice-range';
import { setCurrentSongs, setKind } from '@/views/detail/store/detail';
import singers from '@/views/discover/c-components/singers';
import { Link } from 'react-router-dom';

interface IProps {
  children?: ReactNode;
}

const PlayerBar: FC<IProps> = (props) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [progress, setProgress] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);
  const [isLock, setIsLock] = useState(true);
  const [playerList, setPlayerList] = useState(false);
  const [lyricShow, setLyricShow] = useState(false);
  const [voiceCtrl, setVoiceCtrl] = useState(false);

  const audioRef: any = useRef(null);

  const dispatch = useAppDispatch();

  const { currentSong, lyric, lyricIndex, playMode, songList } = useAppSelector(
    (state) => ({
      currentSong: state.player.currentSong,
      lyric: state.player.lyric,
      lyricIndex: state.player.lyricIndex,
      playMode: state.player.playMode,
      songList: state.player.SongList,
    }),
    shallowEqualApp
  );

  // 总时间
  const songTime = currentSong.dt / 1000;

  // 当目前的歌曲改变时 ， 重新获取 src
  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.src = getPlayUrl(currentSong.id);
    }
  }, [currentSong]);
  // 当当前歌曲变化时自动播放
  useEffect(() => {
    if (currentSong.id) {
      // 确保有有效的歌曲ID
      setIsPlaying(true);
    }
  }, [currentSong.id]);
  // 播放/ 暂停
  const handlePlayBtn = useCallback(() => {
    setIsPlaying(!isPlaying);
  }, [isPlaying]);

  // 提取 播放/暂停的方法,依赖 currentSong
  // 实现 即使 切换歌曲 ，播放状态同步
  useEffect(() => {
    if (audioRef.current) {
      if (isPlaying) {
        audioRef.current.play();
      } else {
        audioRef.current.pause();
      }
    }
  }, [isPlaying, currentSong]);

  // 模式切换
  const handleLoopClick = useCallback(() => {
    let newState = playMode + 1;
    if (newState > 2) newState = 0;
    dispatch(setPlayMode(newState));
  }, [playMode]);

  // 当 audio time 变化时同步到 自定义组件
  const handleOnTimeUpdate = () => {
    setCurrentTime(audioRef.current.currentTime);
    setProgress((audioRef.current.currentTime / songTime) * 100);
    if (lyric.length == 0) return;
    let index = lyric.length - 1;
    let cts = audioRef.current.currentTime * 1000;
    // 找到目前的歌词
    for (let i = 0; i < lyric.length; ++i) {
      if (lyric[i].time > cts) {
        break;
      }
      index = i;
    }
    // 不同再更新
    if (index !== lyricIndex) {
      dispatch(setLyricIndex(index));
      // 在全局样式中修改了 message 的 样式
      if (lyricShow) {
        message.open({
          content: lyric[index].lyric,
          key: 'lyric', // 设置相同的 key , 会替换之前的
          duration: 0, // 不消失
        });
      }
    }
  };
  // 关闭歌词
  const closeLyricMessage = useCallback(() => {
    if (lyricShow) {
      message.destroy('lyric');
    }
    setLyricShow(!lyricShow);
  }, [lyricShow]);
  // 点击触发进度条
  const handleonChangeComplete = useCallback((val: number) => {
    // setProgress(val);
  }, []);

  // Slider 设置 value 后成为 受控组件，需要onChange 来响应
  const handleSliderChange = useCallback(
    (val: number) => {
      if (val >= 0 && val <= 100 && isFinite(songTime)) {
        setProgress(val);
        let ct = (val * songTime) / 100;
        if (isFinite(ct)) {
          setCurrentTime(ct);
          audioRef.current.currentTime = ct;
        }
      }
    },
    [songTime]
  );

  // audio
  // 切换目前的歌曲 （上/下一首）
  const handleMusicChange = useCallback((isNext: boolean) => {
    dispatch(changeCurrentSong(isNext));
  }, []);

  // 当歌曲结束时
  const handleOnEnded = useCallback(() => {
    if (playMode === 1) {
      audioRef.current.currentTime = 0;
    } else {
      dispatch(changeCurrentSong(true));
    }
  }, []);

  // 音量调节
  // 定义 rangeRef 和 btnRef 的类型
  const btnRef = useRef<HTMLSpanElement | null>(null);
  const rangeRef = useRef<HTMLDivElement | null>(null);

  const handleVoiceClick = useCallback((e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    if (audioRef.current && rangeRef.current) {
      const rect = rangeRef.current.getBoundingClientRect();
      const offsetX = e.nativeEvent.offsetX;
      const width = rect.width;
      const volume = Math.min(Math.max(offsetX / width, 0), 1);
      audioRef.current.volume = volume;
      if (btnRef.current) {
        btnRef.current.style.top = `${volume * 100}%`;
      }
    }
  }, []);

  // 点击名字跳转到单曲界面
  function handleNameClick() {
    let description = '';
    for (let i = 0; i < lyric.length; ++i) {
      description += lyric[i].lyric + '\n';
    }
    dispatch(
      setCurrentSongs({
        id: currentSong.id,
        description,
        picUrl: currentSong.al.picUrl,
        name: currentSong.name,
      })
    );
    dispatch(setKind('music'));
  }

  return (
    <PlayerBarAWrapper>
      <PlayerBarWrapper className={'visible ' + (isLock || playerList ? 'lock' : 'nolock')}>
        <div className="sprite_player bg"></div>
        <PlayerBarContentWrapper>
          <div className="btns">
            <a title="上一首" className="sprite_player prev" onClick={() => handleMusicChange(true)}></a>
            <a
              title="播放/暂停"
              className={'sprite_player ' + (isPlaying ? 'play' : 'pause')}
              onClick={handlePlayBtn}
            ></a>
            <a title="下一首" className="sprite_player nxt" onClick={() => handleMusicChange(false)}></a>
          </div>
          <div className="image">
            <img src={currentSong.al?.picUrl} />
            <a className="sprite_player "></a>
          </div>
          <PlayerWrapper>
            <div className="song_info">
              <Link to="/detail" onClick={handleNameClick}>
                {currentSong?.name}
              </Link>
              <a>{currentSong && currentSong.ar && currentSong.ar.length > 0 ? currentSong.ar[0].name : '未知歌手'}</a>
              <a className="sprite_player from_songs"></a>
            </div>
            <Slider
              tooltip={{ formatter: null }}
              value={progress}
              step={0.5}
              onChangeComplete={handleonChangeComplete}
              onChange={handleSliderChange}
            />
            <span>
              <em>{formatTime(currentTime)}</em> / {formatTime(songTime)}
            </span>
          </PlayerWrapper>
          <OperWrapper>
            <a title="歌词" className="show" onClick={closeLyricMessage}></a>
            <a title="收藏" className="sprite_player like"></a>
            <a title="分享" className="sprite_player share"></a>
          </OperWrapper>
          <CtrlWrapper $playMode={playMode}>
            <a
              title="声音"
              className="sprite_player voice"
              onClick={(e) => {
                e.preventDefault();
                setVoiceCtrl(!voiceCtrl);
              }}
            ></a>
            <a title="播放模式" className="sprite_player loop" onClick={handleLoopClick}></a>
            <span className="play_list">
              {/* <span className="sprite_player">{songList.length}</span> */}
              <a
                title="播放列表"
                className="sprite_player"
                onClick={() => {
                  setPlayerList(!playerList);
                }}
              >
                {songList.length}
              </a>
            </span>
            <a title="音质" className="audio_quality quality"></a>
          </CtrlWrapper>
        </PlayerBarContentWrapper>
        <audio id="audio" ref={audioRef} onTimeUpdate={handleOnTimeUpdate} onEnded={handleOnEnded} preload="auto" />
        <div className="vb sprite_player">
          <a
            title="锁定"
            className="sprite_player"
            href="#"
            onClick={(e) => {
              e.preventDefault(); // 阻止默认的跳转行为
              setIsLock(!isLock);
            }}
          ></a>
        </div>
        <div className="bg_2 sprite_player"></div>
      </PlayerBarWrapper>
      <PlayerbarList
        className={playerList ? 'active' : ''}
        setPlayerList={() => {
          setPlayerList(!playerList);
        }}
      ></PlayerbarList>
      <VoiceRange className={voiceCtrl ? 'voice-show' : ''}></VoiceRange>
    </PlayerBarAWrapper>
  );
};

export default memo(PlayerBar);
